extends Node


const SCENE_TRANSITION_SCREEN = preload("res://levels/scene_transition_screen/scene_transition_screen.tscn")
const CAMERA_2D = preload("res://levels/camera_2d.tscn")
const PLAYER = preload("res://characters/yuno/yuno.tscn")
const SMOOTH_CAM_SCENE_PARENT = preload("res://levels/smooth_cam_scene_parent.tscn")

var current_scene: Node2D = null


func transfer_2_target_scene(target_scene_path, target_entry_name):
	GameManager.player_input_locked = true
	
	var current_scene_player: Player = get_tree().current_scene.find_child("Player", true, false) 
	
	# add scene transition screen
	var scene_transition_screen = SCENE_TRANSITION_SCREEN.instantiate()
	get_tree().root.add_child(scene_transition_screen)
	scene_transition_screen.fade_in()
	await get_tree().create_timer(scene_transition_screen.fade_duration).timeout
	
	# scene transition
	get_tree().current_scene.queue_free()
	var smooth_cam_scene_parent = SMOOTH_CAM_SCENE_PARENT.instantiate()
	var scene_inst:Node2D = load(target_scene_path).instantiate()
	current_scene = scene_inst
	smooth_cam_scene_parent.find_child("SubViewport").add_child(scene_inst)
	get_tree().root.add_child(smooth_cam_scene_parent)
	get_tree().current_scene = smooth_cam_scene_parent
	
	var target_entry: Marker2D = scene_inst.find_child(target_entry_name, true, false) as Marker2D
	var target_player: Player = scene_inst.find_child("Player", true, false) as Player
	var target_cam: Camera2D = scene_inst.find_child("Camera2D", true, false) as Camera2D
	
	if not target_player:
		var new_player = PLAYER.instantiate()
		new_player.name = "Player"
		scene_inst.add_child(new_player)
		target_player = new_player
		
	if not target_cam:
		var cam = CAMERA_2D.instantiate()
		scene_inst.add_child(cam)
		target_cam = cam
	
	#cam limit
	var cam_limit: Node2D = scene_inst.find_child("CamLimit", true, false) as Node2D
	if cam_limit:
		target_cam.cam_limit = cam_limit
		target_cam.set_cam_limit()
	
	#follow
	var cam_fixed_point: Node2D = scene_inst.find_child("CamFixedPoint", true, false) as Node2D
	if cam_fixed_point:
		target_cam.fixed_point = cam_fixed_point
	else:
		target_cam.follow_target = target_player
		
	#cam smooth offset
	target_cam.set_cam_offset.connect(smooth_cam_scene_parent.set_cam_offset)
	
	if target_player and target_entry:
		target_player.set_pos(target_entry.global_position)
		if current_scene_player:
			target_player.set_face(current_scene_player.get_face())
		target_cam.follow_immediate()
		
	if scene_inst.has_method("init"):
		scene_inst.call("init")
	
	await get_tree().create_timer(scene_transition_screen.fade_duration).timeout
	scene_transition_screen.fade_out()
	await get_tree().create_timer(scene_transition_screen.fade_duration).timeout
	scene_transition_screen.queue_free()
	
	GameManager.player_input_locked = false
		
		
